Triangle point¶
In this example we will see how to determine if a point is inside a triangle.
We shall start by defining the Triangle class.
Algorithm¶
- The
Triangleclass calculates several values during initialization, such asbax,bay,cax,cay,ax,ay, andden. - These values are derived from the coordinates of the triangle's vertices (p1, p2, p3).
- The
isInsidemethod then takes a pointpas input and uses these pre-calculated values to compute two barycentric coordinates,w1andw2.
The point p is considered inside the triangle if the following conditions are met:
w1 <= 0.0w2 >= 0.0(w1 + w2) >= 1.0
This method determines if the point lies within the triangle's boundaries based on its barycentric coordinates relative to the triangle's vertices.
In [4]:
class Triangle:
def __init__(self, p1, p2, p3):
self.bax = p2[0] - p1[0]
self.bay = p2[1] - p1[1]
self.cax = p3[0] - p1[0]
self.cay = p3[1] - p1[1]
self.ay = p1[1]
self.ax = p1[0] * self.cay
self.den = self.bay * self.cax - self.bax * self.cay
def isInside(self, p):
w1 = self.ax + (p[1] - self.ay) - p[0] * self.cay
w1 /= self.den
w2 = p[1] - self.ay - w1 * self.bay
w2 /= self.cay
return w1 <=0.0 and w2 >=0.0 and (w1 + w2)>=1.0
Driver Code¶
In [5]:
if __name__ == "__main__":
tr = Triangle((4.0, -4.0), (12.0, 6.0), (16.0, -2.0))
points = [
(4.0, -6.0),
(6.0, 4.0),
(6.0, -2.0),
(8.0, -2.0),
(10.0, 2.0),
(10.0, -4.0),
(12.0, 2.0),
(12.0, -2.0),
(12.0, -4.0),
(14.0, -4.0),
(14.0, 0.0)
]
for p in points:
if(tr.isInside(p)):
print(p,"is inside the triangle")
else:
print(p,"is outside the triangle")
(4.0, -6.0) is outside the triangle (6.0, 4.0) is outside the triangle (6.0, -2.0) is inside the triangle (8.0, -2.0) is inside the triangle (10.0, 2.0) is inside the triangle (10.0, -4.0) is outside the triangle (12.0, 2.0) is inside the triangle (12.0, -2.0) is inside the triangle (12.0, -4.0) is outside the triangle (14.0, -4.0) is outside the triangle (14.0, 0.0) is inside the triangle